<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Scope;
class Post extends Model
{
	//两者二选一即可
    // protected $guarded = [];//不可以注入的字段
    protected $fillable = ['title','content','user_id'];//可以注入的字段

    //关联用户
    public function user(){
    	// return $this->belongsTo('\App\User','user_id','id');
    	// return $this->belongsTo(\App\User::class, 'user_id', 'id');
    	return $this->belongsTo('\App\User');//模型关联，model 外键 post的主键
    }

    //评论模型
    public function comments(){
    	return $this->hasMany('\App\Comment')->orderBy('created_at','desc');
    }

    //赞 关联
    public function zan($user_id){
    	return $this->hasOne(\App\Zan::class)->where('user_id',$user_id);
    }
    //文章的所有赞
    public function zans(){
    	return $this->hasMany(\App\Zan::class);
    }

    //属于某一个作者的文章
    public function scopeAuthorBy($query, $user_id)
    {
        return $query->where('user_id', $user_id);
    }
    public function postTopics(){
        return $this->hasMany(\App\PostTopic::class, 'post_id', 'id');
    }

    //不属于某一个专题的文章
    public function scopeTopicNotBy($query, $topic_id)
    {
        return $query->doesntHave('postTopics', 'and', function($q) use($topic_id) {
            $q->where('topic_id',$topic_id);
        });
    }
    //全局scope的方式
    protected static function boot(){
        parent::boot();
        static::addGlobalScope('avaiable', function(Builder $builder)
        {
            $builder->whereIn('status',[0,1]);
        });
    }
}
